<?php defined('SYSPATH') or die('No direct script access.');

/**
 * @file user.php
 * @brief 用户管理
 * @author Lionel Tsai
 * @version 1.0
 * @date 2012-02-17
 */
class Controller_User extends Controller_Rest {
	public function before()
	{
		parent::before();
	}
	/**
	 * @brief 获取user
	 *
	 * @param $user_id
	 *
	 * @return $this
	 */
	public function action_get($user_id=null)
	{
		if($user_id === null)
			$this->get_users();
		else
			$this->get_user($user_id);
	}

	/**
	 * @brief 获取指定用户
	 *
	 * @param $user_id
	 *
	 * @return $this
	 */
	private function get_user($user_id)
	{
		$user = ORM::factory('user', $user_id);

		if(!$user->id)
		{
			$this->response->body("user not found")->status(206);
			return;
		}
		$ret_user = json_encode($user->as_array());
		$this->response->body($ret_user)->status(200);
	}

	/**
	 * @brief 获取指定起止行数 指定角色的所有用户
	 *
	 * @return $this
	 */
	private function get_users()
	{
		//$user = ORM::factory('user');
		/** 获取请求的起止条数*/
		$start = filter_input(INPUT_GET, 'start', FILTER_VALIDATE_INT);
		$pos = filter_input(INPUT_GET, 'pos', FILTER_VALIDATE_INT);
		/** 请求用户所属角色*/
		$type = filter_input(INPUT_GET, 'type');
		if( $type !== 'admin') { $type = 'login';}

		$role = ORM::factory('role', array('name' => $type));
		/** 所有当前角色用户条数*/
		$rset['total_count'] = $role->users->count_all();

		$start = ($start !== null) ? $start : 0;
		$pos = ($pos !== null) ? $pos : $rset['total_count'];
		
		$users = $role 
				->users
				->offset($start)
				->limit($pos)
				->find_all();

		if(!$users->count())
		{
			$this->response->body("no {$type} user exist")->status(206);
			return;
		}
		else
		{
			$rset['num'] = $users->count();
			$rset['list'] = array();
			foreach($users as $user)
			{
				$rset['list'][] = $user->as_array();
			}
			$json_rset = json_encode($rset);
			$this->response->body($json_rset)->status(200);
		}
	}

	/**
	 * @brief 新增user 及user对应的role信息
	 *
	 * @return $this
	 */
	public function action_post()
	{
		$user = ORM::factory('user');

		if(!$_POST) return;

		if(isset($_POST['id']))
		{
			unset($_POST['id']);
		}
		
		try {
			/** 提交user*/
			$user->values($_POST)->check();
			$user->save();

			/** 设置user role*/
			$user->add('roles', ORM::factory('role', array('name' => 'login')));
		}
		catch(ORM_Validation_Exception  $e)
		{
			$errors = $e->errors();
			foreach($errors as $k => $v)
			{
				$this->response->body($k.':not available')->status(206);
			}
			//$this->response->body($e->getMessage())->status(202);
		}
	}

	/**
	 * @brief 更新user基本信息以及user的role,
	 * 更新用户时传值{type[],username,...},
	 * type即role值,可多个
	 *
	 * @param $user_id
	 *
	 * @return 
	 */
	public function action_put($user_id)
	{
		$user = ORM::factory('user', $user_id);
		if(!$user->id)
		{
			$this->response->body('user not exist')->status(206);
			return;
		}

		try {
			/** add user roles*/
			$types = $this->request->post('types');
			if($types !== NULL)
			{
				$user->remove('roles');
				foreach($types as $type)
				{/** add every role*/
					switch($type) {
						case 'admin':{
										$newrole = ORM::factory('role', array('name' => $type));
										$user->add('roles', $newrole);
										break;
									 }
					}
				}
				/** if has login role*/
				$rolelogin = $user->has('roles',ORM::factory('role',array('name'=>'login'))->id);
				if(!$rolelogin)
					$user->add('roles', ORM::factory('role', array('name' => 'login')));
			}
			$user->values($this->request->post())->check()->update();

			$this->response->body($user->password)->status(200);
		}
		catch(ORM_Validation_Exception $e) {
			/** 验证错误*/
			$error = $e->errors();
			foreach($error as $k => $v)
			{
				$this->response->body($k.':not available')->status(206);
			}
		}
		catch(Exception $err) {
			/** 其他错误*/
			$this->response->body($err->getMessage())->status(500);
		}
	}

	/**
	 * @brief 删除指定用户
	 *
	 * @param $user_id
	 *
	 * @return $this
	 */
	public function action_delete($user_id)
	{
		$user = ORM::factory('user', $user_id);
		if(!$user->id)
		{
			$this->response->body('user not exist')->status(206);
			return;
		}
		$user->delete();
		$this->response->status(200);
	}
} // End Userpass
